package com.aizhixin.lab.course.template.service;

import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.common.core.DataValidity;
import com.aizhixin.lab.course.template.domain.TemplateChapterDomain;
import com.aizhixin.lab.course.template.domain.TemplateChapterFileDomain;
import com.aizhixin.lab.course.template.dto.*;
import com.aizhixin.lab.course.template.entity.Template;
import com.aizhixin.lab.course.template.entity.TemplateChapter;
import com.aizhixin.lab.course.template.entity.TemplateChapterFile;
import com.aizhixin.lab.course.template.repository.TemplateChapterFileRepository;
import com.aizhixin.lab.course.template.repository.TemplateChapterRepository;
import com.aizhixin.lab.course.template.repository.TemplateRepository;
import com.aizhixin.lab.docker.domain.ChapterImagesDomain;
import com.aizhixin.lab.docker.service.ChapterImagesService;
import com.aizhixin.lab.project.course.uilt.NumToChinese;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Slf4j
@Service
@Transactional
public class TemplateChapterService {
    @Autowired
    private TemplateChapterRepository chapterRepository;
    @Autowired
    private TemplateChapterFileRepository chapterFileRepository;
    @Autowired
    private TemplateRepository templateRepository;
    @Autowired
    private ChapterImagesService chapterImagesService;
    public List<TemplateChapter> getList(Long templateId) {
        return chapterRepository.findByTemplateIdAndParentIdIsNullOrderByOrderNo(templateId);
    }
    public List<TemplateChapter> findChapterByChapterId(Long chapterId) {
        return chapterRepository.findByParentIdAndDeleteFlag(chapterId,DataValidity.VALID.getState());
    }
    public List<TemplateChapterDomain> getListWithFile(Long templateId) {
        List<TemplateChapter> list = chapterRepository.findByTemplateIdAndParentIdIsNullOrderByOrderNo(templateId);
        List<TemplateChapterDomain> result = setTemplateChapterDomain(list);
        return result;
    }

    private List<TemplateChapterDomain> setTemplateChapterDomain(List<TemplateChapter> list) {
        List<TemplateChapterDomain> result = new ArrayList<>();
        if (!list.isEmpty()) {
            for (TemplateChapter item : list) {
                TemplateChapterDomain d = new TemplateChapterDomain();
                BeanUtils.copyProperties(item, d);
                List<TemplateChapterFile> files = chapterFileRepository.findByChapterIdOrderByNo(item.getId());
                if (!files.isEmpty()) {
                    Map<Integer, Integer> fileCountMap = new HashMap<>();
                    List<TemplateChapterFileDomain> fileDomains = new ArrayList<>();
                    for (TemplateChapterFile file : files) {
                        TemplateChapterFileDomain fd = new TemplateChapterFileDomain();
                        BeanUtils.copyProperties(file, fd);
                        fileDomains.add(fd);
                        Integer fileCount = fileCountMap.get(fd.getType());
                        if (fileCount == null) {
                            fileCount = 0;
                        }
                        fileCountMap.put(fd.getType(), fileCount + 1);
                    }
                    d.setFiles(fileDomains);
                    d.setFileCounts(fileCountMap);
                }
                if (item.getChildrens() != null && !item.getChildrens().isEmpty()) {
                    List<TemplateChapterDomain> children = setTemplateChapterDomain(item.getChildrens());
                    d.setChildrens(children);
                }
                result.add(d);
            }
        }
        return result;
    }

    public Map<String, Object> add(TemplateChapterAddDTO dto) {
        Template template = templateRepository.findByIdAndDeleteFlag(dto.getTemplateId(), DataValidity.VALID.getState());
        ChapterImagesDomain chapterImagesDomain = new ChapterImagesDomain();
        TemplateChapter chapter = new TemplateChapter();
        BeanUtils.copyProperties(dto, chapter);
        if (chapter.getParentId() != null && chapter.getParentId() == 0) {
            chapter.setParentId(null);
        }
        chapter.setIsExp(false);
        if (!Objects.isNull(template)){
            if (template.getIsDefaultEx()==1){
                chapter.setIsExp(true);
                chapter.setVmName(template.getVmName());
                chapter.setVmNum(template.getVmNum());

            }
        }
        String no = chapter.getChapterNo().replaceAll("\\.","");
        chapter.setOrderNo(Integer.parseInt(no));
        if (chapter.getParentId() == null || chapter.getParentId() == 0) {
            chapter.setChineseOrderNo(NumToChinese.numToChinese(chapter.getChapterNo()));
        }

        chapter = chapterRepository.save(chapter);
        if (chapter.getIsExp()){
            chapterImagesDomain.setCourseId(dto.getTemplateId().toString());
            chapterImagesDomain.setChapterId(chapter.getId());
            chapterImagesDomain.setImageName(chapter.getVmName());
            chapterImagesDomain.setNum(chapter.getVmNum());
            chapterImagesService.saveChapterImages(chapterImagesDomain);
        }
        updateTemplateChapterCount(dto.getTemplateId());
        Map<String, Object> result = new HashMap<>();
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, chapter);
        return result;
    }

    public void updateTemplateChapterCount(Long templateId) {
        Template template = templateRepository.findOne(templateId);
        if (template != null) {
            int countChapter = chapterRepository.countByTemplateIdAndType(templateId, 10);
            int countSection = chapterRepository.countByTemplateIdAndType(templateId, 20);
            template.setCountChapter(countChapter);
            template.setCountSection(countSection);
            templateRepository.save(template);
        }
    }

    public Map<String, Object> save(TemplateChapterDTO dto) {
        Map<String, Object> result = new HashMap<>();
        TemplateChapter chapter = chapterRepository.findByIdAndDeleteFlag(dto.getId(), DataValidity.VALID.getState());
        if (chapter != null) {
            BeanUtils.copyProperties(dto, chapter);
            chapterRepository.save(chapter);
            result.put(ApiReturnConstants.SUCCESS, true);
        } else {
            result.put(ApiReturnConstants.SUCCESS, false);
        }
        return result;
    }

    public Map<String, Object> saveSort(TemplateChapterSortDTO dto) {
        Map<String, Object> result = new HashMap<>();
        saveChapterSort(dto.getList());
        updateTemplateChapterCount(dto.getTemplateId());
        result.put(ApiReturnConstants.SUCCESS, true);
        return result;
    }

    private void saveChapterSort(List<TemplateChapterSortItemDTO> list) {
        if (list != null && !list.isEmpty()) {
            for (TemplateChapterSortItemDTO item : list) {
                TemplateChapter chapter = chapterRepository.findByIdAndDeleteFlag(item.getId(), DataValidity.VALID.getState());
                if (chapter != null) {
                    if (item.getParentId() == null || item.getParentId() < 1) {
                        chapter.setParentId(null);
                        chapter.setChineseOrderNo(NumToChinese.numToChinese(item.getChapterNo()));
                    } else {
                        chapter.setParentId(item.getParentId());
                    }
                    chapter.setChapterNo(item.getChapterNo());
                    String no = chapter.getChapterNo().replaceAll("\\.", "");
                    chapter.setOrderNo(Integer.parseInt(no));
                    chapterRepository.save(chapter);
                    if (item.getChildrens() != null && !item.getChildrens().isEmpty()) {
                        saveChapterSort(item.getChildrens());
                    }
                }
            }
        }
    }

    public Map<String, Object> delete(Long chapterId) {
        Map<String, Object> result = new HashMap<>();
        TemplateChapter chapter = chapterRepository.findByIdAndDeleteFlag(chapterId, DataValidity.VALID.getState());
        if (chapter != null) {
            deleteByParentId(chapter.getId());
            deleteFiles(chapter.getId());
            chapterRepository.delete(chapter);
            updateChapterNo(chapter.getParentId(), chapter.getChapterNo(),chapter.getTemplateId());
            updateTemplateChapterCount(chapter.getTemplateId());
            result.put(ApiReturnConstants.SUCCESS, true);
        } else {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "没有章节信息");
        }
        return result;
    }

    private void updateChapterNo(Long parentId, String chapterNo,Long templateId) {
        BigDecimal no = new BigDecimal(chapterNo);
        List<TemplateChapter> chapters = chapterRepository.findByParentIdAndDeleteFlagAndTemplateId(parentId,DataValidity.VALID.getState(),templateId);
        if (chapters != null && !chapters.isEmpty()) {
            List<TemplateChapter> list = new ArrayList<>();
            for (TemplateChapter chapter : chapters) {
                BigDecimal itemNo = new BigDecimal(chapter.getChapterNo());
                if (itemNo.compareTo(no) == 1) {
                    if (chapter.getChapterNo().indexOf(".") > 0) {
                        chapter.setChapterNo(itemNo.subtract(new BigDecimal(0.01)).setScale(2, RoundingMode.HALF_UP) + "");
                    } else {
                        chapter.setChapterNo(itemNo.subtract(new BigDecimal(1)).intValue() + "");
                        List<TemplateChapter> items = chapterRepository.findByParentId(chapter.getId());
                        if (items != null && !items.isEmpty()) {
                            for (TemplateChapter item : items) {
                                String noStr = item.getChapterNo();
                                String[] nos = noStr.split("\\.");
                                item.setChapterNo(chapter.getChapterNo() + "." + nos[1]);
                                list.add(item);
                            }
                        }
                    }
                    String noStr = chapter.getChapterNo().replaceAll("\\.","");
                    chapter.setOrderNo(Integer.parseInt(noStr));
                    chapter.setChineseOrderNo(NumToChinese.numToChinese(chapter.getChapterNo()));
                    list.add(chapter);
                }
            }
            if (!list.isEmpty()) {
                chapterRepository.save(list);
            }
        }
    }

    private void deleteByParentId(Long parentId) {
        List<TemplateChapter> chapters = chapterRepository.findByParentId(parentId);
        if (chapters != null && !chapters.isEmpty()) {
            for (TemplateChapter chapter : chapters) {
                deleteByParentId(chapter.getId());
                deleteFiles(chapter.getId());
                chapterRepository.delete(chapter);
            }
        }
    }

    public List<TemplateChapterFile> getFileList(Long chapterId) {
        return chapterFileRepository.findByChapterIdOrderByNo(chapterId);
    }

    public Map<String, Object> saveFile(TemplateChapterFileDTO dto) {
        Map<String, Object> result = new HashMap<>();
        TemplateChapterFile file = null;
        if (dto.getId() != null && dto.getId().longValue() > 0) {
            file = chapterFileRepository.findOne(dto.getId());
        }
        if (file == null) {
            file = new TemplateChapterFile();
        }
        BeanUtils.copyProperties(dto, file);
        if (file.getId() == null || file.getId().longValue() < 1) {
            Integer maxNo = getFileNoMin(file.getChapterId());
            file.setNo(maxNo - 1);
        }
        file = chapterFileRepository.save(file);
        result.put(ApiReturnConstants.SUCCESS, true);
        result.put(ApiReturnConstants.DATA, file);
        return result;
    }

    private Integer getFileNoMin(Long chapterId) {
        List<TemplateChapterFile> list = chapterFileRepository.findByChapterIdOrderByNo(chapterId);
        if (list != null && !list.isEmpty()) {
            TemplateChapterFile file = list.get(0);
            if (file != null && file.getNo() != null) {
                return file.getNo();
            } else {
                return 0;
            }
        } else {
            return 0;
        }
    }

    public Map<String, Object> saveFileOrder(TemplateChapterFileOrderListDTO dto) {
        Map<String, Object> result = new HashMap<>();
        if (dto != null && dto.getList() != null && !dto.getList().isEmpty()) {
            Map<Long, Integer> map = new HashMap<>();
            for (TemplateChapterFileOrderDTO item : dto.getList()) {
                map.put(item.getId(), item.getNo());
            }
            List<TemplateChapterFile> list = chapterFileRepository.findByChapterIdOrderByNo(dto.getChapterId());
            if (!list.isEmpty()) {
                for (TemplateChapterFile file : list) {
                    Integer no = map.get(file.getId());
                    if (no != null) {
                        file.setNo(no);
                    }
                }
                chapterFileRepository.save(list);
            }
            result.put(ApiReturnConstants.SUCCESS, true);
        } else {
            result.put(ApiReturnConstants.SUCCESS, false);
        }
        return result;
    }

    public Map<String, Object> deleteFile(Long fileId) {
        Map<String, Object> result = new HashMap<>();
        TemplateChapterFile file = chapterFileRepository.findOne(fileId);
        if (file != null) {
            chapterFileRepository.delete(file);
            result.put(ApiReturnConstants.SUCCESS, true);
        } else {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "没有文件信息");
        }
        return result;
    }

    private void deleteFiles(Long chapterId) {
        List<TemplateChapterFile> files = chapterFileRepository.findByChapterIdOrderByNo(chapterId);
        if (files != null) {
            chapterFileRepository.delete(files);
        }
    }
}
